home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / logging / handlers.pyc (.txt) < prev   
Python Compiled Bytecode  |  2009-11-11  |  38KB  |  1,208 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. """
  5. Additional handlers for the logging package for Python. The core package is
  6. based on PEP 282 and comments thereto in comp.lang.python, and influenced by
  7. Apache's log4j system.
  8.  
  9. Copyright (C) 2001-2009 Vinay Sajip. All Rights Reserved.
  10.  
  11. To use, simply 'import logging.handlers' and log away!
  12. """
  13. import logging
  14. import socket
  15. import types
  16. import os
  17. import string
  18. import cPickle
  19. import struct
  20. import time
  21. import re
  22. from stat import ST_DEV, ST_INO
  23.  
  24. try:
  25.     import codecs
  26. except ImportError:
  27.     codecs = None
  28.  
  29. DEFAULT_TCP_LOGGING_PORT = 9020
  30. DEFAULT_UDP_LOGGING_PORT = 9021
  31. DEFAULT_HTTP_LOGGING_PORT = 9022
  32. DEFAULT_SOAP_LOGGING_PORT = 9023
  33. SYSLOG_UDP_PORT = 514
  34. _MIDNIGHT = 86400
  35.  
  36. class BaseRotatingHandler(logging.FileHandler):
  37.     '''
  38.     Base class for handlers that rotate log files at a certain point.
  39.     Not meant to be instantiated directly.  Instead, use RotatingFileHandler
  40.     or TimedRotatingFileHandler.
  41.     '''
  42.     
  43.     def __init__(self, filename, mode, encoding = None, delay = 0):
  44.         '''
  45.         Use the specified filename for streamed logging
  46.         '''
  47.         if codecs is None:
  48.             encoding = None
  49.         
  50.         logging.FileHandler.__init__(self, filename, mode, encoding, delay)
  51.         self.mode = mode
  52.         self.encoding = encoding
  53.  
  54.     
  55.     def emit(self, record):
  56.         '''
  57.         Emit a record.
  58.  
  59.         Output the record to the file, catering for rollover as described
  60.         in doRollover().
  61.         '''
  62.         
  63.         try:
  64.             if self.shouldRollover(record):
  65.                 self.doRollover()
  66.             
  67.             logging.FileHandler.emit(self, record)
  68.         except (KeyboardInterrupt, SystemExit):
  69.             raise 
  70.         except:
  71.             self.handleError(record)
  72.  
  73.  
  74.  
  75.  
  76. class RotatingFileHandler(BaseRotatingHandler):
  77.     '''
  78.     Handler for logging to a set of files, which switches from one file
  79.     to the next when the current file reaches a certain size.
  80.     '''
  81.     
  82.     def __init__(self, filename, mode = 'a', maxBytes = 0, backupCount = 0, encoding = None, delay = 0):
  83.         '''
  84.         Open the specified file and use it as the stream for logging.
  85.  
  86.         By default, the file grows indefinitely. You can specify particular
  87.         values of maxBytes and backupCount to allow the file to rollover at
  88.         a predetermined size.
  89.  
  90.         Rollover occurs whenever the current log file is nearly maxBytes in
  91.         length. If backupCount is >= 1, the system will successively create
  92.         new files with the same pathname as the base file, but with extensions
  93.         ".1", ".2" etc. appended to it. For example, with a backupCount of 5
  94.         and a base file name of "app.log", you would get "app.log",
  95.         "app.log.1", "app.log.2", ... through to "app.log.5". The file being
  96.         written to is always "app.log" - when it gets filled up, it is closed
  97.         and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.
  98.         exist, then they are renamed to "app.log.2", "app.log.3" etc.
  99.         respectively.
  100.  
  101.         If maxBytes is zero, rollover never occurs.
  102.         '''
  103.         if maxBytes > 0:
  104.             mode = 'a'
  105.         
  106.         BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
  107.         self.maxBytes = maxBytes
  108.         self.backupCount = backupCount
  109.  
  110.     
  111.     def doRollover(self):
  112.         '''
  113.         Do a rollover, as described in __init__().
  114.         '''
  115.         self.stream.close()
  116.         if self.backupCount > 0:
  117.             for i in range(self.backupCount - 1, 0, -1):
  118.                 sfn = '%s.%d' % (self.baseFilename, i)
  119.                 dfn = '%s.%d' % (self.baseFilename, i + 1)
  120.                 if os.path.exists(sfn):
  121.                     if os.path.exists(dfn):
  122.                         os.remove(dfn)
  123.                     
  124.                     os.rename(sfn, dfn)
  125.                     continue
  126.             
  127.             dfn = self.baseFilename + '.1'
  128.             if os.path.exists(dfn):
  129.                 os.remove(dfn)
  130.             
  131.             os.rename(self.baseFilename, dfn)
  132.         
  133.         self.mode = 'w'
  134.         self.stream = self._open()
  135.  
  136.     
  137.     def shouldRollover(self, record):
  138.         '''
  139.         Determine if rollover should occur.
  140.  
  141.         Basically, see if the supplied record would cause the file to exceed
  142.         the size limit we have.
  143.         '''
  144.         if self.stream is None:
  145.             self.stream = self._open()
  146.         
  147.         if self.maxBytes > 0:
  148.             msg = '%s\n' % self.format(record)
  149.             self.stream.seek(0, 2)
  150.             if self.stream.tell() + len(msg) >= self.maxBytes:
  151.                 return 1
  152.         
  153.         return 0
  154.  
  155.  
  156.  
  157. class TimedRotatingFileHandler(BaseRotatingHandler):
  158.     '''
  159.     Handler for logging to a file, rotating the log file at certain timed
  160.     intervals.
  161.  
  162.     If backupCount is > 0, when rollover is done, no more than backupCount
  163.     files are kept - the oldest ones are deleted.
  164.     '''
  165.     
  166.     def __init__(self, filename, when = 'h', interval = 1, backupCount = 0, encoding = None, delay = 0, utc = 0):
  167.         BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay)
  168.         self.when = string.upper(when)
  169.         self.backupCount = backupCount
  170.         self.utc = utc
  171.         currentTime = int(time.time())
  172.         if self.when == 'S':
  173.             self.interval = 1
  174.             self.suffix = '%Y-%m-%d_%H-%M-%S'
  175.             self.extMatch = '^\\d{4}-\\d{2}-\\d{2}_\\d{2}-\\d{2}-\\d{2}$'
  176.         elif self.when == 'M':
  177.             self.interval = 60
  178.             self.suffix = '%Y-%m-%d_%H-%M'
  179.             self.extMatch = '^\\d{4}-\\d{2}-\\d{2}_\\d{2}-\\d{2}$'
  180.         elif self.when == 'H':
  181.             self.interval = 3600
  182.             self.suffix = '%Y-%m-%d_%H'
  183.             self.extMatch = '^\\d{4}-\\d{2}-\\d{2}_\\d{2}$'
  184.         elif self.when == 'D' or self.when == 'MIDNIGHT':
  185.             self.interval = 86400
  186.             self.suffix = '%Y-%m-%d'
  187.             self.extMatch = '^\\d{4}-\\d{2}-\\d{2}$'
  188.         elif self.when.startswith('W'):
  189.             self.interval = 604800
  190.             if len(self.when) != 2:
  191.                 raise ValueError('You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s' % self.when)
  192.             len(self.when) != 2
  193.             if self.when[1] < '0' or self.when[1] > '6':
  194.                 raise ValueError('Invalid day specified for weekly rollover: %s' % self.when)
  195.             self.when[1] > '6'
  196.             self.dayOfWeek = int(self.when[1])
  197.             self.suffix = '%Y-%m-%d'
  198.             self.extMatch = '^\\d{4}-\\d{2}-\\d{2}$'
  199.         else:
  200.             raise ValueError('Invalid rollover interval specified: %s' % self.when)
  201.         self.extMatch = (self.when == 'MIDNIGHT').compile(self.extMatch)
  202.         self.interval = self.interval * interval
  203.         self.rolloverAt = self.computeRollover(int(time.time()))
  204.  
  205.     
  206.     def computeRollover(self, currentTime):
  207.         '''
  208.         Work out the rollover time based on the specified time.
  209.         '''
  210.         result = currentTime + self.interval
  211.         if self.when == 'MIDNIGHT' or self.when.startswith('W'):
  212.             if self.utc:
  213.                 t = time.gmtime(currentTime)
  214.             else:
  215.                 t = time.localtime(currentTime)
  216.             currentHour = t[3]
  217.             currentMinute = t[4]
  218.             currentSecond = t[5]
  219.             r = _MIDNIGHT - (currentHour * 60 + currentMinute) * 60 + currentSecond
  220.             result = currentTime + r
  221.             if self.when.startswith('W'):
  222.                 day = t[6]
  223.                 if day != self.dayOfWeek:
  224.                     if day < self.dayOfWeek:
  225.                         daysToWait = self.dayOfWeek - day
  226.                     else:
  227.                         daysToWait = (6 - day) + self.dayOfWeek + 1
  228.                     newRolloverAt = result + daysToWait * 86400
  229.                     if not self.utc:
  230.                         dstNow = t[-1]
  231.                         dstAtRollover = time.localtime(newRolloverAt)[-1]
  232.                         if dstNow != dstAtRollover:
  233.                             if not dstNow:
  234.                                 newRolloverAt = newRolloverAt - 3600
  235.                             else:
  236.                                 newRolloverAt = newRolloverAt + 3600
  237.                         
  238.                     
  239.                     result = newRolloverAt
  240.                 
  241.             
  242.         
  243.         return result
  244.  
  245.     
  246.     def shouldRollover(self, record):
  247.         '''
  248.         Determine if rollover should occur.
  249.  
  250.         record is not used, as we are just comparing times, but it is needed so
  251.         the method signatures are the same
  252.         '''
  253.         t = int(time.time())
  254.         if t >= self.rolloverAt:
  255.             return 1
  256.         return 0
  257.  
  258.     
  259.     def getFilesToDelete(self):
  260.         '''
  261.         Determine the files to delete when rolling over.
  262.  
  263.         More specific than the earlier method, which just used glob.glob().
  264.         '''
  265.         (dirName, baseName) = os.path.split(self.baseFilename)
  266.         fileNames = os.listdir(dirName)
  267.         result = []
  268.         prefix = baseName + '.'
  269.         plen = len(prefix)
  270.         for fileName in fileNames:
  271.             if fileName[:plen] == prefix:
  272.                 suffix = fileName[plen:]
  273.                 if self.extMatch.match(suffix):
  274.                     result.append(os.path.join(dirName, fileName))
  275.                 
  276.             self.extMatch.match(suffix)
  277.         
  278.         result.sort()
  279.         if len(result) < self.backupCount:
  280.             result = []
  281.         else:
  282.             result = result[:len(result) - self.backupCount]
  283.         return result
  284.  
  285.     
  286.     def doRollover(self):
  287.         '''
  288.         do a rollover; in this case, a date/time stamp is appended to the filename
  289.         when the rollover happens.  However, you want the file to be named for the
  290.         start of the interval, not the current time.  If there is a backup count,
  291.         then we have to get a list of matching filenames, sort them and remove
  292.         the one with the oldest suffix.
  293.         '''
  294.         if self.stream:
  295.             self.stream.close()
  296.         
  297.         t = self.rolloverAt - self.interval
  298.         if self.utc:
  299.             timeTuple = time.gmtime(t)
  300.         else:
  301.             timeTuple = time.localtime(t)
  302.         dfn = self.baseFilename + '.' + time.strftime(self.suffix, timeTuple)
  303.         if os.path.exists(dfn):
  304.             os.remove(dfn)
  305.         
  306.         os.rename(self.baseFilename, dfn)
  307.         if self.backupCount > 0:
  308.             for s in self.getFilesToDelete():
  309.                 os.remove(s)
  310.             
  311.         
  312.         self.mode = 'w'
  313.         self.stream = self._open()
  314.         currentTime = int(time.time())
  315.         newRolloverAt = self.computeRollover(currentTime)
  316.         while newRolloverAt <= currentTime:
  317.             newRolloverAt = newRolloverAt + self.interval
  318.         if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not (self.utc):
  319.             dstNow = time.localtime(currentTime)[-1]
  320.             dstAtRollover = time.localtime(newRolloverAt)[-1]
  321.             if dstNow != dstAtRollover:
  322.                 if not dstNow:
  323.                     newRolloverAt = newRolloverAt - 3600
  324.                 else:
  325.                     newRolloverAt = newRolloverAt + 3600
  326.             
  327.         
  328.         self.rolloverAt = newRolloverAt
  329.  
  330.  
  331.  
  332. class WatchedFileHandler(logging.FileHandler):
  333.     '''
  334.     A handler for logging to a file, which watches the file
  335.     to see if it has changed while in use. This can happen because of
  336.     usage of programs such as newsyslog and logrotate which perform
  337.     log file rotation. This handler, intended for use under Unix,
  338.     watches the file to see if it has changed since the last emit.
  339.     (A file has changed if its device or inode have changed.)
  340.     If it has changed, the old file stream is closed, and the file
  341.     opened to get a new stream.
  342.  
  343.     This handler is not appropriate for use under Windows, because
  344.     under Windows open files cannot be moved or renamed - logging
  345.     opens the files with exclusive locks - and so there is no need
  346.     for such a handler. Furthermore, ST_INO is not supported under
  347.     Windows; stat always returns zero for this value.
  348.  
  349.     This handler is based on a suggestion and patch by Chad J.
  350.     Schroeder.
  351.     '''
  352.     
  353.     def __init__(self, filename, mode = 'a', encoding = None, delay = 0):
  354.         logging.FileHandler.__init__(self, filename, mode, encoding, delay)
  355.         if not os.path.exists(self.baseFilename):
  356.             (self.dev, self.ino) = (-1, -1)
  357.         else:
  358.             stat = os.stat(self.baseFilename)
  359.             self.dev = stat[ST_DEV]
  360.             self.ino = stat[ST_INO]
  361.  
  362.     
  363.     def emit(self, record):
  364.         '''
  365.         Emit a record.
  366.  
  367.         First check if the underlying file has changed, and if it
  368.         has, close the old stream and reopen the file to get the
  369.         current stream.
  370.         '''
  371.         if not os.path.exists(self.baseFilename):
  372.             stat = None
  373.             changed = 1
  374.         else:
  375.             stat = os.stat(self.baseFilename)
  376.             if not stat[ST_DEV] != self.dev:
  377.                 pass
  378.             changed = stat[ST_INO] != self.ino
  379.         if changed and self.stream is not None:
  380.             self.stream.flush()
  381.             self.stream.close()
  382.             self.stream = self._open()
  383.             if stat is None:
  384.                 stat = os.stat(self.baseFilename)
  385.             
  386.             self.dev = stat[ST_DEV]
  387.             self.ino = stat[ST_INO]
  388.         
  389.         logging.FileHandler.emit(self, record)
  390.  
  391.  
  392.  
  393. class SocketHandler(logging.Handler):
  394.     """
  395.     A handler class which writes logging records, in pickle format, to
  396.     a streaming socket. The socket is kept open across logging calls.
  397.     If the peer resets it, an attempt is made to reconnect on the next call.
  398.     The pickle which is sent is that of the LogRecord's attribute dictionary
  399.     (__dict__), so that the receiver does not need to have the logging module
  400.     installed in order to process the logging event.
  401.  
  402.     To unpickle the record at the receiving end into a LogRecord, use the
  403.     makeLogRecord function.
  404.     """
  405.     
  406.     def __init__(self, host, port):
  407.         """
  408.         Initializes the handler with a specific host address and port.
  409.  
  410.         The attribute 'closeOnError' is set to 1 - which means that if
  411.         a socket error occurs, the socket is silently closed and then
  412.         reopened on the next logging call.
  413.         """
  414.         logging.Handler.__init__(self)
  415.         self.host = host
  416.         self.port = port
  417.         self.sock = None
  418.         self.closeOnError = 0
  419.         self.retryTime = None
  420.         self.retryStart = 1
  421.         self.retryMax = 30
  422.         self.retryFactor = 2
  423.  
  424.     
  425.     def makeSocket(self, timeout = 1):
  426.         '''
  427.         A factory method which allows subclasses to define the precise
  428.         type of socket they want.
  429.         '''
  430.         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  431.         if hasattr(s, 'settimeout'):
  432.             s.settimeout(timeout)
  433.         
  434.         s.connect((self.host, self.port))
  435.         return s
  436.  
  437.     
  438.     def createSocket(self):
  439.         '''
  440.         Try to create a socket, using an exponential backoff with
  441.         a max retry time. Thanks to Robert Olson for the original patch
  442.         (SF #815911) which has been slightly refactored.
  443.         '''
  444.         now = time.time()
  445.         if self.retryTime is None:
  446.             attempt = 1
  447.         else:
  448.             attempt = now >= self.retryTime
  449.         if attempt:
  450.             
  451.             try:
  452.                 self.sock = self.makeSocket()
  453.                 self.retryTime = None
  454.             except socket.error:
  455.                 if self.retryTime is None:
  456.                     self.retryPeriod = self.retryStart
  457.                 else:
  458.                     self.retryPeriod = self.retryPeriod * self.retryFactor
  459.                     if self.retryPeriod > self.retryMax:
  460.                         self.retryPeriod = self.retryMax
  461.                     
  462.                 self.retryTime = now + self.retryPeriod
  463.             except:
  464.                 None<EXCEPTION MATCH>socket.error
  465.             
  466.  
  467.         None<EXCEPTION MATCH>socket.error
  468.  
  469.     
  470.     def send(self, s):
  471.         '''
  472.         Send a pickled string to the socket.
  473.  
  474.         This function allows for partial sends which can happen when the
  475.         network is busy.
  476.         '''
  477.         if self.sock is None:
  478.             self.createSocket()
  479.         
  480.         if self.sock:
  481.             
  482.             try:
  483.                 if hasattr(self.sock, 'sendall'):
  484.                     self.sock.sendall(s)
  485.                 else:
  486.                     sentsofar = 0
  487.                     left = len(s)
  488.                     while left > 0:
  489.                         sent = self.sock.send(s[sentsofar:])
  490.                         sentsofar = sentsofar + sent
  491.                         left = left - sent
  492.             except socket.error:
  493.                 self.sock.close()
  494.                 self.sock = None
  495.             except:
  496.                 None<EXCEPTION MATCH>socket.error
  497.             
  498.  
  499.         None<EXCEPTION MATCH>socket.error
  500.  
  501.     
  502.     def makePickle(self, record):
  503.         '''
  504.         Pickles the record in binary format with a length prefix, and
  505.         returns it ready for transmission across the socket.
  506.         '''
  507.         ei = record.exc_info
  508.         if ei:
  509.             dummy = self.format(record)
  510.             record.exc_info = None
  511.         
  512.         s = cPickle.dumps(record.__dict__, 1)
  513.         if ei:
  514.             record.exc_info = ei
  515.         
  516.         slen = struct.pack('>L', len(s))
  517.         return slen + s
  518.  
  519.     
  520.     def handleError(self, record):
  521.         '''
  522.         Handle an error during logging.
  523.  
  524.         An error has occurred during logging. Most likely cause -
  525.         connection lost. Close the socket so that we can retry on the
  526.         next event.
  527.         '''
  528.         if self.closeOnError and self.sock:
  529.             self.sock.close()
  530.             self.sock = None
  531.         else:
  532.             logging.Handler.handleError(self, record)
  533.  
  534.     
  535.     def emit(self, record):
  536.         '''
  537.         Emit a record.
  538.  
  539.         Pickles the record and writes it to the socket in binary format.
  540.         If there is an error with the socket, silently drop the packet.
  541.         If there was a problem with the socket, re-establishes the
  542.         socket.
  543.         '''
  544.         
  545.         try:
  546.             s = self.makePickle(record)
  547.             self.send(s)
  548.         except (KeyboardInterrupt, SystemExit):
  549.             raise 
  550.         except:
  551.             self.handleError(record)
  552.  
  553.  
  554.     
  555.     def close(self):
  556.         '''
  557.         Closes the socket.
  558.         '''
  559.         if self.sock:
  560.             self.sock.close()
  561.             self.sock = None
  562.         
  563.         logging.Handler.close(self)
  564.  
  565.  
  566.  
  567. class DatagramHandler(SocketHandler):
  568.     """
  569.     A handler class which writes logging records, in pickle format, to
  570.     a datagram socket.  The pickle which is sent is that of the LogRecord's
  571.     attribute dictionary (__dict__), so that the receiver does not need to
  572.     have the logging module installed in order to process the logging event.
  573.  
  574.     To unpickle the record at the receiving end into a LogRecord, use the
  575.     makeLogRecord function.
  576.  
  577.     """
  578.     
  579.     def __init__(self, host, port):
  580.         '''
  581.         Initializes the handler with a specific host address and port.
  582.         '''
  583.         SocketHandler.__init__(self, host, port)
  584.         self.closeOnError = 0
  585.  
  586.     
  587.     def makeSocket(self):
  588.         '''
  589.         The factory method of SocketHandler is here overridden to create
  590.         a UDP socket (SOCK_DGRAM).
  591.         '''
  592.         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  593.         return s
  594.  
  595.     
  596.     def send(self, s):
  597.         '''
  598.         Send a pickled string to a socket.
  599.  
  600.         This function no longer allows for partial sends which can happen
  601.         when the network is busy - UDP does not guarantee delivery and
  602.         can deliver packets out of sequence.
  603.         '''
  604.         if self.sock is None:
  605.             self.createSocket()
  606.         
  607.         self.sock.sendto(s, (self.host, self.port))
  608.  
  609.  
  610.  
  611. class SysLogHandler(logging.Handler):
  612.     """
  613.     A handler class which sends formatted logging records to a syslog
  614.     server. Based on Sam Rushing's syslog module:
  615.     http://www.nightmare.com/squirl/python-ext/misc/syslog.py
  616.     Contributed by Nicolas Untz (after which minor refactoring changes
  617.     have been made).
  618.     """
  619.     LOG_EMERG = 0
  620.     LOG_ALERT = 1
  621.     LOG_CRIT = 2
  622.     LOG_ERR = 3
  623.     LOG_WARNING = 4
  624.     LOG_NOTICE = 5
  625.     LOG_INFO = 6
  626.     LOG_DEBUG = 7
  627.     LOG_KERN = 0
  628.     LOG_USER = 1
  629.     LOG_MAIL = 2
  630.     LOG_DAEMON = 3
  631.     LOG_AUTH = 4
  632.     LOG_SYSLOG = 5
  633.     LOG_LPR = 6
  634.     LOG_NEWS = 7
  635.     LOG_UUCP = 8
  636.     LOG_CRON = 9
  637.     LOG_AUTHPRIV = 10
  638.     LOG_LOCAL0 = 16
  639.     LOG_LOCAL1 = 17
  640.     LOG_LOCAL2 = 18
  641.     LOG_LOCAL3 = 19
  642.     LOG_LOCAL4 = 20
  643.     LOG_LOCAL5 = 21
  644.     LOG_LOCAL6 = 22
  645.     LOG_LOCAL7 = 23
  646.     priority_names = {
  647.         'alert': LOG_ALERT,
  648.         'crit': LOG_CRIT,
  649.         'critical': LOG_CRIT,
  650.         'debug': LOG_DEBUG,
  651.         'emerg': LOG_EMERG,
  652.         'err': LOG_ERR,
  653.         'error': LOG_ERR,
  654.         'info': LOG_INFO,
  655.         'notice': LOG_NOTICE,
  656.         'panic': LOG_EMERG,
  657.         'warn': LOG_WARNING,
  658.         'warning': LOG_WARNING }
  659.     facility_names = {
  660.         'auth': LOG_AUTH,
  661.         'authpriv': LOG_AUTHPRIV,
  662.         'cron': LOG_CRON,
  663.         'daemon': LOG_DAEMON,
  664.         'kern': LOG_KERN,
  665.         'lpr': LOG_LPR,
  666.         'mail': LOG_MAIL,
  667.         'news': LOG_NEWS,
  668.         'security': LOG_AUTH,
  669.         'syslog': LOG_SYSLOG,
  670.         'user': LOG_USER,
  671.         'uucp': LOG_UUCP,
  672.         'local0': LOG_LOCAL0,
  673.         'local1': LOG_LOCAL1,
  674.         'local2': LOG_LOCAL2,
  675.         'local3': LOG_LOCAL3,
  676.         'local4': LOG_LOCAL4,
  677.         'local5': LOG_LOCAL5,
  678.         'local6': LOG_LOCAL6,
  679.         'local7': LOG_LOCAL7 }
  680.     priority_map = {
  681.         'DEBUG': 'debug',
  682.         'INFO': 'info',
  683.         'WARNING': 'warning',
  684.         'ERROR': 'error',
  685.         'CRITICAL': 'critical' }
  686.     
  687.     def __init__(self, address = ('localhost', SYSLOG_UDP_PORT), facility = LOG_USER):
  688.         '''
  689.         Initialize a handler.
  690.  
  691.         If address is specified as a string, a UNIX socket is used. To log to a
  692.         local syslogd, "SysLogHandler(address="/dev/log")" can be used.
  693.         If facility is not specified, LOG_USER is used.
  694.         '''
  695.         logging.Handler.__init__(self)
  696.         self.address = address
  697.         self.facility = facility
  698.         if type(address) == types.StringType:
  699.             self.unixsocket = 1
  700.             self._connect_unixsocket(address)
  701.         else:
  702.             self.unixsocket = 0
  703.             self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  704.         self.formatter = None
  705.  
  706.     
  707.     def _connect_unixsocket(self, address):
  708.         self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
  709.         
  710.         try:
  711.             self.socket.connect(address)
  712.         except socket.error:
  713.             self.socket.close()
  714.             self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  715.             self.socket.connect(address)
  716.  
  717.  
  718.     log_format_string = '<%d>%s\x00'
  719.     
  720.     def encodePriority(self, facility, priority):
  721.         '''
  722.         Encode the facility and priority. You can pass in strings or
  723.         integers - if strings are passed, the facility_names and
  724.         priority_names mapping dictionaries are used to convert them to
  725.         integers.
  726.         '''
  727.         if type(facility) == types.StringType:
  728.             facility = self.facility_names[facility]
  729.         
  730.         if type(priority) == types.StringType:
  731.             priority = self.priority_names[priority]
  732.         
  733.         return facility << 3 | priority
  734.  
  735.     
  736.     def close(self):
  737.         '''
  738.         Closes the socket.
  739.         '''
  740.         if self.unixsocket:
  741.             self.socket.close()
  742.         
  743.         logging.Handler.close(self)
  744.  
  745.     
  746.     def mapPriority(self, levelName):
  747.         """
  748.         Map a logging level name to a key in the priority_names map.
  749.         This is useful in two scenarios: when custom levels are being
  750.         used, and in the case where you can't do a straightforward
  751.         mapping by lowercasing the logging level name because of locale-
  752.         specific issues (see SF #1524081).
  753.         """
  754.         return self.priority_map.get(levelName, 'warning')
  755.  
  756.     
  757.     def emit(self, record):
  758.         '''
  759.         Emit a record.
  760.  
  761.         The record is formatted, and then sent to the syslog server. If
  762.         exception information is present, it is NOT sent to the server.
  763.         '''
  764.         msg = self.format(record)
  765.         msg = self.log_format_string % (self.encodePriority(self.facility, self.mapPriority(record.levelname)), msg)
  766.         
  767.         try:
  768.             if self.unixsocket:
  769.                 
  770.                 try:
  771.                     self.socket.send(msg)
  772.                 except socket.error:
  773.                     self._connect_unixsocket(self.address)
  774.                     self.socket.send(msg)
  775.                 except:
  776.                     None<EXCEPTION MATCH>socket.error
  777.                 
  778.  
  779.             None<EXCEPTION MATCH>socket.error
  780.             self.socket.sendto(msg, self.address)
  781.         except (KeyboardInterrupt, SystemExit):
  782.             raise 
  783.         except:
  784.             self.handleError(record)
  785.  
  786.  
  787.  
  788.  
  789. class SMTPHandler(logging.Handler):
  790.     '''
  791.     A handler class which sends an SMTP email for each logging event.
  792.     '''
  793.     
  794.     def __init__(self, mailhost, fromaddr, toaddrs, subject, credentials = None):
  795.         '''
  796.         Initialize the handler.
  797.  
  798.         Initialize the instance with the from and to addresses and subject
  799.         line of the email. To specify a non-standard SMTP port, use the
  800.         (host, port) tuple format for the mailhost argument. To specify
  801.         authentication credentials, supply a (username, password) tuple
  802.         for the credentials argument.
  803.         '''
  804.         logging.Handler.__init__(self)
  805.         if type(mailhost) == types.TupleType:
  806.             (self.mailhost, self.mailport) = mailhost
  807.         else:
  808.             self.mailhost = mailhost
  809.             self.mailport = None
  810.         if type(credentials) == types.TupleType:
  811.             (self.username, self.password) = credentials
  812.         else:
  813.             self.username = None
  814.         self.fromaddr = fromaddr
  815.         if type(toaddrs) == types.StringType:
  816.             toaddrs = [
  817.                 toaddrs]
  818.         
  819.         self.toaddrs = toaddrs
  820.         self.subject = subject
  821.  
  822.     
  823.     def getSubject(self, record):
  824.         '''
  825.         Determine the subject for the email.
  826.  
  827.         If you want to specify a subject line which is record-dependent,
  828.         override this method.
  829.         '''
  830.         return self.subject
  831.  
  832.     weekdayname = [
  833.         'Mon',
  834.         'Tue',
  835.         'Wed',
  836.         'Thu',
  837.         'Fri',
  838.         'Sat',
  839.         'Sun']
  840.     monthname = [
  841.         None,
  842.         'Jan',
  843.         'Feb',
  844.         'Mar',
  845.         'Apr',
  846.         'May',
  847.         'Jun',
  848.         'Jul',
  849.         'Aug',
  850.         'Sep',
  851.         'Oct',
  852.         'Nov',
  853.         'Dec']
  854.     
  855.     def date_time(self):
  856.         '''
  857.         Return the current date and time formatted for a MIME header.
  858.         Needed for Python 1.5.2 (no email package available)
  859.         '''
  860.         (year, month, day, hh, mm, ss, wd, y, z) = time.gmtime(time.time())
  861.         s = '%s, %02d %3s %4d %02d:%02d:%02d GMT' % (self.weekdayname[wd], day, self.monthname[month], year, hh, mm, ss)
  862.         return s
  863.  
  864.     
  865.     def emit(self, record):
  866.         '''
  867.         Emit a record.
  868.  
  869.         Format the record and send it to the specified addressees.
  870.         '''
  871.         
  872.         try:
  873.             import smtplib as smtplib
  874.             
  875.             try:
  876.                 formatdate = formatdate
  877.                 import email.utils
  878.             except ImportError:
  879.                 formatdate = self.date_time
  880.  
  881.             port = self.mailport
  882.             if not port:
  883.                 port = smtplib.SMTP_PORT
  884.             
  885.             smtp = smtplib.SMTP(self.mailhost, port)
  886.             msg = self.format(record)
  887.             msg = 'From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s' % (self.fromaddr, string.join(self.toaddrs, ','), self.getSubject(record), formatdate(), msg)
  888.             if self.username:
  889.                 smtp.login(self.username, self.password)
  890.             
  891.             smtp.sendmail(self.fromaddr, self.toaddrs, msg)
  892.             smtp.quit()
  893.         except (KeyboardInterrupt, SystemExit):
  894.             raise 
  895.         except:
  896.             self.handleError(record)
  897.  
  898.  
  899.  
  900.  
  901. class NTEventLogHandler(logging.Handler):
  902.     '''
  903.     A handler class which sends events to the NT Event Log. Adds a
  904.     registry entry for the specified application name. If no dllname is
  905.     provided, win32service.pyd (which contains some basic message
  906.     placeholders) is used. Note that use of these placeholders will make
  907.     your event logs big, as the entire message source is held in the log.
  908.     If you want slimmer logs, you have to pass in the name of your own DLL
  909.     which contains the message definitions you want to use in the event log.
  910.     '''
  911.     
  912.     def __init__(self, appname, dllname = None, logtype = 'Application'):
  913.         logging.Handler.__init__(self)
  914.         
  915.         try:
  916.             import win32evtlogutil as win32evtlogutil
  917.             import win32evtlog as win32evtlog
  918.             self.appname = appname
  919.             self._welu = win32evtlogutil
  920.             if not dllname:
  921.                 dllname = os.path.split(self._welu.__file__)
  922.                 dllname = os.path.split(dllname[0])
  923.                 dllname = os.path.join(dllname[0], 'win32service.pyd')
  924.             
  925.             self.dllname = dllname
  926.             self.logtype = logtype
  927.             self._welu.AddSourceToRegistry(appname, dllname, logtype)
  928.             self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE
  929.             self.typemap = {
  930.                 logging.DEBUG: win32evtlog.EVENTLOG_INFORMATION_TYPE,
  931.                 logging.INFO: win32evtlog.EVENTLOG_INFORMATION_TYPE,
  932.                 logging.WARNING: win32evtlog.EVENTLOG_WARNING_TYPE,
  933.                 logging.ERROR: win32evtlog.EVENTLOG_ERROR_TYPE,
  934.                 logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE }
  935.         except ImportError:
  936.             print 'The Python Win32 extensions for NT (service, event logging) appear not to be available.'
  937.             self._welu = None
  938.  
  939.  
  940.     
  941.     def getMessageID(self, record):
  942.         '''
  943.         Return the message ID for the event record. If you are using your
  944.         own messages, you could do this by having the msg passed to the
  945.         logger being an ID rather than a formatting string. Then, in here,
  946.         you could use a dictionary lookup to get the message ID. This
  947.         version returns 1, which is the base message ID in win32service.pyd.
  948.         '''
  949.         return 1
  950.  
  951.     
  952.     def getEventCategory(self, record):
  953.         '''
  954.         Return the event category for the record.
  955.  
  956.         Override this if you want to specify your own categories. This version
  957.         returns 0.
  958.         '''
  959.         return 0
  960.  
  961.     
  962.     def getEventType(self, record):
  963.         """
  964.         Return the event type for the record.
  965.  
  966.         Override this if you want to specify your own types. This version does
  967.         a mapping using the handler's typemap attribute, which is set up in
  968.         __init__() to a dictionary which contains mappings for DEBUG, INFO,
  969.         WARNING, ERROR and CRITICAL. If you are using your own levels you will
  970.         either need to override this method or place a suitable dictionary in
  971.         the handler's typemap attribute.
  972.         """
  973.         return self.typemap.get(record.levelno, self.deftype)
  974.  
  975.     
  976.     def emit(self, record):
  977.         '''
  978.         Emit a record.
  979.  
  980.         Determine the message ID, event category and event type. Then
  981.         log the message in the NT event log.
  982.         '''
  983.         if self._welu:
  984.             
  985.             try:
  986.                 id = self.getMessageID(record)
  987.                 cat = self.getEventCategory(record)
  988.                 type = self.getEventType(record)
  989.                 msg = self.format(record)
  990.                 self._welu.ReportEvent(self.appname, id, cat, type, [
  991.                     msg])
  992.             except (KeyboardInterrupt, SystemExit):
  993.                 raise 
  994.             except:
  995.                 None<EXCEPTION MATCH>(KeyboardInterrupt, SystemExit)
  996.                 self.handleError(record)
  997.             
  998.  
  999.         None<EXCEPTION MATCH>(KeyboardInterrupt, SystemExit)
  1000.  
  1001.     
  1002.     def close(self):
  1003.         '''
  1004.         Clean up this handler.
  1005.  
  1006.         You can remove the application name from the registry as a
  1007.         source of event log entries. However, if you do this, you will
  1008.         not be able to see the events as you intended in the Event Log
  1009.         Viewer - it needs to be able to access the registry to get the
  1010.         DLL name.
  1011.         '''
  1012.         logging.Handler.close(self)
  1013.  
  1014.  
  1015.  
  1016. class HTTPHandler(logging.Handler):
  1017.     '''
  1018.     A class which sends records to a Web server, using either GET or
  1019.     POST semantics.
  1020.     '''
  1021.     
  1022.     def __init__(self, host, url, method = 'GET'):
  1023.         '''
  1024.         Initialize the instance with the host, the request URL, and the method
  1025.         ("GET" or "POST")
  1026.         '''
  1027.         logging.Handler.__init__(self)
  1028.         method = string.upper(method)
  1029.         if method not in ('GET', 'POST'):
  1030.             raise ValueError, 'method must be GET or POST'
  1031.         method not in ('GET', 'POST')
  1032.         self.host = host
  1033.         self.url = url
  1034.         self.method = method
  1035.  
  1036.     
  1037.     def mapLogRecord(self, record):
  1038.         '''
  1039.         Default implementation of mapping the log record into a dict
  1040.         that is sent as the CGI data. Overwrite in your class.
  1041.         Contributed by Franz  Glasner.
  1042.         '''
  1043.         return record.__dict__
  1044.  
  1045.     
  1046.     def emit(self, record):
  1047.         '''
  1048.         Emit a record.
  1049.  
  1050.         Send the record to the Web server as an URL-encoded dictionary
  1051.         '''
  1052.         
  1053.         try:
  1054.             import httplib as httplib
  1055.             import urllib as urllib
  1056.             host = self.host
  1057.             h = httplib.HTTP(host)
  1058.             url = self.url
  1059.             data = urllib.urlencode(self.mapLogRecord(record))
  1060.             if self.method == 'GET':
  1061.                 if string.find(url, '?') >= 0:
  1062.                     sep = '&'
  1063.                 else:
  1064.                     sep = '?'
  1065.                 url = url + '%c%s' % (sep, data)
  1066.             
  1067.             h.putrequest(self.method, url)
  1068.             i = string.find(host, ':')
  1069.             if i >= 0:
  1070.                 host = host[:i]
  1071.             
  1072.             h.putheader('Host', host)
  1073.             if self.method == 'POST':
  1074.                 h.putheader('Content-type', 'application/x-www-form-urlencoded')
  1075.                 h.putheader('Content-length', str(len(data)))
  1076.             
  1077.             h.endheaders()
  1078.             if self.method == 'POST':
  1079.                 h.send(data)
  1080.             
  1081.             h.getreply()
  1082.         except (KeyboardInterrupt, SystemExit):
  1083.             raise 
  1084.         except:
  1085.             self.handleError(record)
  1086.  
  1087.  
  1088.  
  1089.  
  1090. class BufferingHandler(logging.Handler):
  1091.     """
  1092.   A handler class which buffers logging records in memory. Whenever each
  1093.   record is added to the buffer, a check is made to see if the buffer should
  1094.   be flushed. If it should, then flush() is expected to do what's needed.
  1095.     """
  1096.     
  1097.     def __init__(self, capacity):
  1098.         '''
  1099.         Initialize the handler with the buffer size.
  1100.         '''
  1101.         logging.Handler.__init__(self)
  1102.         self.capacity = capacity
  1103.         self.buffer = []
  1104.  
  1105.     
  1106.     def shouldFlush(self, record):
  1107.         '''
  1108.         Should the handler flush its buffer?
  1109.  
  1110.         Returns true if the buffer is up to capacity. This method can be
  1111.         overridden to implement custom flushing strategies.
  1112.         '''
  1113.         return len(self.buffer) >= self.capacity
  1114.  
  1115.     
  1116.     def emit(self, record):
  1117.         '''
  1118.         Emit a record.
  1119.  
  1120.         Append the record. If shouldFlush() tells us to, call flush() to process
  1121.         the buffer.
  1122.         '''
  1123.         self.buffer.append(record)
  1124.         if self.shouldFlush(record):
  1125.             self.flush()
  1126.         
  1127.  
  1128.     
  1129.     def flush(self):
  1130.         '''
  1131.         Override to implement custom flushing behaviour.
  1132.  
  1133.         This version just zaps the buffer to empty.
  1134.         '''
  1135.         self.buffer = []
  1136.  
  1137.     
  1138.     def close(self):
  1139.         """
  1140.         Close the handler.
  1141.  
  1142.         This version just flushes and chains to the parent class' close().
  1143.         """
  1144.         self.flush()
  1145.         logging.Handler.close(self)
  1146.  
  1147.  
  1148.  
  1149. class MemoryHandler(BufferingHandler):
  1150.     '''
  1151.     A handler class which buffers logging records in memory, periodically
  1152.     flushing them to a target handler. Flushing occurs whenever the buffer
  1153.     is full, or when an event of a certain severity or greater is seen.
  1154.     '''
  1155.     
  1156.     def __init__(self, capacity, flushLevel = logging.ERROR, target = None):
  1157.         '''
  1158.         Initialize the handler with the buffer size, the level at which
  1159.         flushing should occur and an optional target.
  1160.  
  1161.         Note that without a target being set either here or via setTarget(),
  1162.         a MemoryHandler is no use to anyone!
  1163.         '''
  1164.         BufferingHandler.__init__(self, capacity)
  1165.         self.flushLevel = flushLevel
  1166.         self.target = target
  1167.  
  1168.     
  1169.     def shouldFlush(self, record):
  1170.         '''
  1171.         Check for buffer full or a record at the flushLevel or higher.
  1172.         '''
  1173.         if not len(self.buffer) >= self.capacity:
  1174.             pass
  1175.         return record.levelno >= self.flushLevel
  1176.  
  1177.     
  1178.     def setTarget(self, target):
  1179.         '''
  1180.         Set the target handler for this handler.
  1181.         '''
  1182.         self.target = target
  1183.  
  1184.     
  1185.     def flush(self):
  1186.         '''
  1187.         For a MemoryHandler, flushing means just sending the buffered
  1188.         records to the target, if there is one. Override if you want
  1189.         different behaviour.
  1190.         '''
  1191.         if self.target:
  1192.             for record in self.buffer:
  1193.                 self.target.handle(record)
  1194.             
  1195.             self.buffer = []
  1196.         
  1197.  
  1198.     
  1199.     def close(self):
  1200.         '''
  1201.         Flush, set the target to None and lose the buffer.
  1202.         '''
  1203.         self.flush()
  1204.         self.target = None
  1205.         BufferingHandler.close(self)
  1206.  
  1207.  
  1208.